<template>
  <div class="user-list-view">
    <h2>用户列表</h2>
    <button class="add-btn" @click="openAdd">新增用户</button>
    <table v-if="users.length" class="user-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>用户名</th>
          <th>真实姓名</th>
          <th>手机号</th>
          <th>邮箱</th>
          <th>部门</th>
          <th>职位</th>
          <th>状态</th>
          <th>注册时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id">
          <td>{{ user.id }}</td>
          <td>{{ user.username }}</td>
          <td>{{ user.realName }}</td>
          <td>{{ user.phoneNumber }}</td>
          <td>{{ user.email }}</td>
          <td>{{ user.department }}</td>
          <td>{{ user.position }}</td>
          <td>
            <span :style="{color: user.status === 1 ? 'green' : 'red'}">
              {{ user.status === 1 ? '启用' : '禁用' }}
            </span>
          </td>
          <td>{{ user.createdAt ? user.createdAt.split('T')[0] : '' }}</td>
          <td>
            <button @click="openEdit(user)">编辑</button>
            <button @click="delUser(user.id)">删除</button>
            <button @click="openGrant(user)">授权</button>
          </td>
        </tr>
      </tbody>
    </table>
    <div v-else>暂无用户数据</div>

    <!-- 新增/编辑弹窗 -->
    <div v-if="showDialog" class="dialog-mask">
      <div class="dialog">
        <h3>{{ editMode ? '编辑用户' : '新增用户' }}</h3>
        <form @submit.prevent="submitForm">
          <div class="form-row">
            <label>用户名：</label>
            <input v-model="form.username" :disabled="editMode" required />
          </div>
          <div class="form-row">
            <label>真实姓名：</label>
            <input v-model="form.realName" />
          </div>
          <div class="form-row">
            <label>手机号：</label>
            <input v-model="form.phoneNumber" />
          </div>
          <div class="form-row">
            <label>邮箱：</label>
            <input v-model="form.email" />
          </div>
          <div class="form-row">
            <label>部门：</label>
            <input v-model="form.department" />
          </div>
          <div class="form-row">
            <label>职位：</label>
            <input v-model="form.position" />
          </div>
          <div class="form-row">
            <label>状态：</label>
            <select v-model.number="form.status">
              <option :value="1">启用</option>
              <option :value="0">禁用</option>
            </select>
          </div>
          <div class="form-row">
            <label>密码：</label>
            <input v-model="form.password" :placeholder="editMode ? '不修改请留空' : '默认123456'" type="password" />
          </div>
          <div class="dialog-actions">
            <button type="submit">保存</button>
            <button type="button" @click="closeDialog">取消</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 授权弹窗 -->
    <div v-if="showGrantDialog" class="dialog-mask">
      <div class="dialog">
        <h3>用户授权</h3>
        <div v-if="roles.length">
          <div v-for="role in roles" :key="role.id" class="form-row">
            <input type="checkbox" :id="'role-' + role.id" v-model="selectedRoleIds" :value="role.id" />
            <label :for="'role-' + role.id">{{ role.name }}</label>
          </div>
        </div>
        <div v-else>暂无角色数据</div>
        <div class="dialog-actions">
          <button @click="saveGrant">确定</button>
          <button @click="closeGrantDialog">取消</button>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="delId !== null" class="dialog-mask">
      <div class="dialog">
        <h3>确认删除</h3>
        <p>确定要删除该用户吗？</p>
        <div class="dialog-actions">
          <button @click="confirmDel">确定</button>
          <button @click="delId = null">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

interface User {
  id?: number
  username: string
  realName: string
  phoneNumber: string
  email: string
  avatarUrl?: string
  department: string
  position: string
  status: number
  password?: string
  createdAt?: string
  updatedAt?: string
}

interface Role {
  id: number
  name: string
  description: string
}

const users = ref<User[]>([])
const roles = ref<Role[]>([])
const showDialog = ref(false)
const showGrantDialog = ref(false)
const editMode = ref(false)
const form = ref<User>({
  username: '',
  realName: '',
  phoneNumber: '',
  email: '',
  department: '',
  position: '',
  status: 1,
  password: ''
})
const delId = ref<number|null>(null)
const selectedRoleIds = ref<number[]>([])
const currentUserId = ref<number|null>(null)

function fetchUsers() {
  const token = localStorage.getItem('token')
  fetch('http://localhost:8080/api/users', {
    headers: {
      'Authorization': token ? `Bearer ${token}` : ''
    }
  })
    .then(res => res.json())
    .then(data => {
      users.value = data
      // 记录访问用户列表日志
      fetch('http://localhost:8080/api/logs', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': token ? `Bearer ${token}` : ''
        },
        body: JSON.stringify({
          action: 'ACCESS_PAGE',
          description: '访问用户列表页面'
        })
      })
    })
}

function fetchRoles() {
  const token = localStorage.getItem('token')
  fetch('http://localhost:8080/api/roles', {
    headers: {
      'Authorization': token ? `Bearer ${token}` : ''
    }
  })
    .then(res => res.json())
    .then(data => {
      roles.value = data
    })
}

onMounted(() => {
  fetchUsers()
  fetchRoles()
})

function openAdd() {
  editMode.value = false
  showDialog.value = true
  form.value = {
    username: '',
    realName: '',
    phoneNumber: '',
    email: '',
    department: '',
    position: '',
    status: 1,
    password: ''
  }
}

function openEdit(user: User) {
  editMode.value = true
  showDialog.value = true
  form.value = { ...user, password: '' }
}

function closeDialog() {
  showDialog.value = false
}

function submitForm() {
  const token = localStorage.getItem('token')
  if (editMode.value) {
    // 编辑
    fetch(`http://localhost:8080/api/users/${form.value.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : ''
      },
      body: JSON.stringify(form.value)
    }).then(res => {
      if (res.ok) {
        // 记录编辑日志
        fetch('http://localhost:8080/api/logs', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': token ? `Bearer ${token}` : ''
          },
          body: JSON.stringify({
            action: 'UPDATE_USER',
            description: `更新用户：${form.value.username}`
          })
        })
        fetchUsers()
        showDialog.value = false
      }
    })
  } else {
    // 新增
    fetch('http://localhost:8080/api/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : ''
      },
      body: JSON.stringify(form.value)
    }).then(res => {
      if (res.ok) {
        // 记录新增日志
        fetch('http://localhost:8080/api/logs', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': token ? `Bearer ${token}` : ''
          },
          body: JSON.stringify({
            action: 'CREATE_USER',
            description: `创建用户：${form.value.username}`
          })
        })
        fetchUsers()
        showDialog.value = false
      }
    })
  }
}

function delUser(id: number | undefined) {
  if (typeof id === 'number') {
    delId.value = id
  }
}

function confirmDel() {
  const token = localStorage.getItem('token')
  fetch(`http://localhost:8080/api/users/${delId.value}`, {
    method: 'DELETE',
    headers: {
      'Authorization': token ? `Bearer ${token}` : ''
    }
  }).then(res => {
    if (res.ok) {
      // 记录删除日志
      fetch('http://localhost:8080/api/logs', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': token ? `Bearer ${token}` : ''
        },
        body: JSON.stringify({
          action: 'DELETE_USER',
          description: `删除用户ID：${delId.value}`
        })
      })
      fetchUsers()
      delId.value = null
    }
  })
}

function openGrant(user: User) {
  if (user.id === undefined) return
  currentUserId.value = user.id
  selectedRoleIds.value = []
  const token = localStorage.getItem('token')
  fetch(`http://localhost:8080/api/users/${user.id}/roles`, {
    headers: {
      'Authorization': token ? `Bearer ${token}` : ''
    }
  })
    .then(res => res.json())
    .then(data => {
      selectedRoleIds.value = data.map((role: Role) => role.id)
      showGrantDialog.value = true
    })
}

function closeGrantDialog() {
  showGrantDialog.value = false
  currentUserId.value = null
}

function saveGrant() {
  if (currentUserId.value === null) return
  const token = localStorage.getItem('token')
  fetch(`http://localhost:8080/api/users/${currentUserId.value}/roles`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token ? `Bearer ${token}` : ''
    },
    body: JSON.stringify(selectedRoleIds.value)
  }).then(res => {
    if (res.ok) {
      showGrantDialog.value = false
      currentUserId.value = null
    }
  })
}
</script>

<style scoped>
.user-list-view {
  padding: 24px;
}
.add-btn {
  margin-bottom: 16px;
  padding: 6px 18px;
  background: #2d8cf0;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.user-table {
  width: 100%;
  border-collapse: collapse;
  background: #fff;
}
.user-table th, .user-table td {
  border: 1px solid #eee;
  padding: 8px 12px;
  text-align: left;
}
.user-table th {
  background: #f5f6fa;
}
.user-table button {
  margin-right: 8px;
  padding: 4px 10px;
  border: none;
  border-radius: 3px;
  background: #eee;
  cursor: pointer;
}
.user-table button:hover {
  background: #d0e6fa;
}
.dialog-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.dialog {
  background: #fff;
  padding: 24px 32px;
  border-radius: 8px;
  min-width: 320px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
.form-row {
  margin-bottom: 14px;
  display: flex;
  align-items: center;
}
.form-row label {
  width: 80px;
  color: #333;
}
.form-row input, .form-row select {
  flex: 1;
  padding: 6px 8px;
  border: 1px solid #ccc;
  border-radius: 3px;
}
.dialog-actions {
  text-align: right;
}
.dialog-actions button {
  margin-left: 12px;
  padding: 6px 18px;
  background: #2d8cf0;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.dialog-actions button:last-child {
  background: #aaa;
}
</style> 